package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserInfoDao;
import entity.UserInfo;

/**
 * 用户信息 Servlet
 *
 * @author bing.zhang06@hand-china.com 2021/7/24 11:20
 **/
@WebServlet(urlPatterns = {"/login", "/logout"}, name = "userInfoServlet")
public class UserInfoServlet extends HttpServlet {
    private UserInfoDao userInfoDao;

    public UserInfoServlet() {
        System.out.println("userInfoServlet constructor...");
        this.userInfoDao = new UserInfoDao();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        if ("/login".equals(requestURI)) {
            login(req, resp);
        } else if ("/logout".equals(requestURI)) {
            logout(req, resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().removeAttribute("info");
        resp.sendRedirect("/login.jsp");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserInfo params = getUserInfo(req, resp);
        UserInfo info = userInfoDao.login(params);
        if (info != null) {
            req.getSession().setAttribute("info", info);
            resp.sendRedirect("/tip/success.jsp");
        } else {
            resp.sendRedirect("/tip/false.jsp");
        }
    }

    private UserInfo getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        int age = Integer.parseInt(req.getParameter("age"));
        String email = req.getParameter("email");
        String[] hobbies = req.getParameterValues("hobby");
        UserInfo userInfo = new UserInfo(name, password, hobbies.toString(), email);
        System.out.println(userInfo);
        return userInfo;
    }
}
